package com.bsoft.service.impl;

import com.bsoft.Exception.CommonException;
import com.bsoft.aop.annotation.MultiDataSourceTransactional;
import com.bsoft.mapper.business.EcgMapper;
import com.bsoft.mapper.business.TreatSystemMapper;
import com.bsoft.service.EcgService;
import com.bsoft.service.TreatSystemService;
import com.bsoft.utils.ConmonUtil;
import com.bsoft.utils.XmlMapUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*;

/**
 * 康复治疗
 */
@Service
@EnableTransactionManagement
public class TreatSystemServiceImpl extends ConmonUtil implements TreatSystemService {
    private static Logger logger = LoggerFactory.getLogger(TreatSystemServiceImpl.class);

    @Resource
    private TreatSystemMapper treatSystemMapper;


    /**
     * =========================================================金堂人民医院=============================================================
     */
    /*治疗系统:获取病人信息接口*/
    @Override
    public String get_Treat_PatientInfo(Map<String, Object> req) throws Exception {
        isNUll(req, Arrays.asList("StartDate", "EndDate"));
        List<Map<String, Object>> treatPatientInfoList = treatSystemMapper.get_Treat_PatientInfo(req);
        return getSuccess(JSONArray.fromObject(treatPatientInfoList));
    }

    /*治疗系统:医嘱信息获取接口*/
    @Override
    public String get_Treat_Orders(Map<String, Object> req) throws Exception {
        isNUll(req, Arrays.asList("PatientId", "DeptCode"));
        List<Map<String, Object>> treatOrdersList = treatSystemMapper.get_Treat_Orders(req);
        treatOrdersList.stream().forEach(t->{
            List<Map<String, Object>>  planList = treatSystemMapper.get_Treat_Orders_Plan((Map<String, Object>) t);//获取医嘱计划
            t.put("OrdersPlanList",planList);
        });
        return getSuccess(JSONArray.fromObject(treatOrdersList));
    }

    /*康复类项目计费:住院医嘱计费*/
    @Override
    public String Treat_OrdersBill(Map<String, Object> parmReqMap) throws Exception {
        Map<String, Object> msgBody = (Map<String, Object>) parmReqMap.get("MsgBody");
        isNUll(msgBody, Arrays.asList("Patient", "Visit", "ExamStatusInfo"));

        Map<String, Object> patientMap = (Map<String, Object>) msgBody.get("Patient");
        Map<String, Object> visitMap = (Map<String, Object>) msgBody.get("Visit");
        Map<String, Object> examStatusInfoMap = (Map<String, Object>) msgBody.get("ExamStatusInfo");

        isNUll(patientMap, Arrays.asList("SourcePatientId", "Name"));
        isNUll(examStatusInfoMap, Arrays.asList("zyh", "ItemList"));

        String zyh = examStatusInfoMap.get("zyh").toString();//住院号
        String patientId = patientMap.get("SourcePatientId").toString();//患者档案ID
        String patientName = patientMap.get("Name").toString();//患者姓名
        int count = 0;

        //获取执行项目
        List<Map<String, Object>> xmList = new ArrayList<>();
        if ((((Map<String, Object>) examStatusInfoMap.get("ItemList")).get("Item")) instanceof List) {
            xmList = (List<Map<String, Object>>) ((Map<String, Object>) examStatusInfoMap.get("ItemList")).get("Item");
        } else {
            xmList.add((Map<String, Object>) ((Map<String, Object>) examStatusInfoMap.get("ItemList")).get("Item"));
        }

        Map<String, Object> commonParmMap = new HashMap<>();
        commonParmMap.put("zyh", zyh);

        for (Map<String, Object> req : xmList) {
            String jhh =req.get("JHH").toString();
            String ysyzbh =req.get("ysyzbh").toString();
            String czgh =req.get("executionCode").toString();

            commonParmMap.clear();
            commonParmMap.put("JHH", jhh);
            commonParmMap.put("CZGH", czgh);
            commonParmMap.put("ysyzbh", ysyzbh);

            //判断操作计费医生基础信息是否存在
            Map<String, Object> ygxxMap = treatSystemMapper.getYgxxInfo(commonParmMap);
            Assert.notNull(ygxxMap, "未找到该医生[" + czgh + "]信息请核实!");

            //根据医嘱本号+住院号获取医嘱信息
            List<Map<String, Object>> bqyzList = treatSystemMapper.getNoSqidBqyz(req);
            Assert.notNull(bqyzList, "未找到相关医嘱信息::YSYZBH" + ysyzbh);

            //判断获取出来的医嘱是否 含有历史医嘱或者临时医嘱
            for (Map<String, Object> bqyzMap : bqyzList) {
                if (Objects.equals("1", bqyzMap.get("LSYZ").toString()) && Objects.equals("1", bqyzMap.get("LSBZ").toString())) {
                    throw new CommonException("该住院号[" + zyh + "]相关医嘱[YSYZBH:" +ysyzbh + "]为历史医嘱[LSBZ:" + bqyzMap.get("LSBZ") + "]和临时医嘱[LSYZ:" + bqyzMap.get("LSYZ") + "]请核实!");
                }
            }

            //更新ZY_BQYZ.Qrsj
            count = treatSystemMapper.updateNoSqidBqyz(req);
            if (count == 0) throw new CommonException("更新[ZY_BQYZ.QRSJ]医嘱[YSYZBH::" +ysyzbh+ "]失败");

            commonParmMap.put("jlxh", getIdentity("zy", "ZY_FYMX", count));
            commonParmMap.put("czgh", czgh);
           /* //先判断物资库存 判断是否需要二级库房出库
            Map<String, Object> wl_xhmx = new HashMap<>();
            List<Map<String, Object>> wz_list = treatSystemMapper.wz1(req);
            req.put("csmc", "WZXHMX_WDZKF_HCJF");
            String WZXHMX_WDZKF_HCJF = treatSystemMapper.getXtcs(xtcsMap("WZXHMX_WDZKF_HCJF"));
            if (WZXHMX_WDZKF_HCJF == null || WZXHMX_WDZKF_HCJF.equals("")) {
                throw new CommonException("'机构未设置WZXHMX_WDZKF_HCJF对应数据来源的系统参数");
            }

            if (wz_list.size() > 0) {
                for (Map<String, Object> wz_map : wz_list) {
                    //查询科室物资库房对照
                    List<Map<String, Object>> ks_list = treatSystemMapper.wz6(wz_map);
                    if ("1".equals(WZXHMX_WDZKF_HCJF) && ks_list.size() < 1) {
                        continue;
                    } else if ("0".equals(WZXHMX_WDZKF_HCJF) && ks_list.size() < 1) {
                        throw new CommonException("ksdm" + wz_map.get("KSDM") + "未对应物资库房");
                    }
                    //查询物资库存是否满足
                    List<Map<String, Object>> wzkc_list = treatSystemMapper.wz2(wz_map);
                    if (wzkc_list.size() < 1) {
                        throw new CommonException("物资库存不足");
                    }
                    wz_map.putAll(wzkc_list.get(0));
                    //更新物资库存
                    count = treatSystemMapper.wz3(wz_map);
                    if (count != 1) {
                        throw new CommonException("物资库存不足,更新物资库存失败");
                    }
                    //写wl_xhmx
                    //10获取记录序号
                    Long jlxh = getIdentity("wl", "WL_XHMX");
                    wl_xhmx.put("jlxh", jlxh);
                    wl_xhmx.put("jgid", "1");
                    wl_xhmx.put("kfxh", wz_map.get("KFXH"));
                    wl_xhmx.put("ksdm", wz_map.get("KSDM"));
                    wl_xhmx.put("ksmc", wz_map.get("KSMC"));
                    wl_xhmx.put("brid", wz_map.get("BRID"));
                    wl_xhmx.put("brhm", wz_map.get("MZHM"));
                    wl_xhmx.put("brly", "2");
                    wl_xhmx.put("brxm", wz_map.get("BRXM"));
                    // wl_xhmx.put("xhrq",);
                    wl_xhmx.put("wzxh", wz_map.get("WZXH"));
                    wl_xhmx.put("wzsl", wz_map.get("YLSL"));
                    wl_xhmx.put("wzjg", wz_map.get("WZJG"));
                    wl_xhmx.put("thsl", 0);
                    wl_xhmx.put("ztbz", 0);
                    wl_xhmx.put("djxh", 0);
                    wl_xhmx.put("sbxh", wz_map.get("YJXH"));
                    wl_xhmx.put("kcxh", wz_map.get("KCXH"));
                    wl_xhmx.put("cjxh", wz_map.get("CJXH"));
                    wl_xhmx.put("yjxh", wz_map.get("SBXH"));
                    count = treatSystemMapper.wz5(wl_xhmx);
                }
            }*/

            //3.zy_fymx写入
            count = treatSystemMapper.saveNoSqidFymx(commonParmMap);
            if (count == 0) throw new CommonException("计费失败:写入[zy_fymx]失败,医嘱计划号[JHH:"+jhh+":ysyzbh"+ysyzbh+"]");

            //2.bq_yzjh更新,查询是否有医嘱计划
            List<Map<String, Object>> yzjhList = treatSystemMapper.getNoSqidYzjh(commonParmMap);
            if (yzjhList.size() == 0) throw new CommonException("未找到相关医嘱[ysyzbh:"+ysyzbh+"]计划[jhh:"+jhh+"]信息!");

            count = treatSystemMapper.upNoSqidYzjh(commonParmMap);
            if (count == 0) throw new CommonException("更新bq_zyjh失败!!::" + req.get("ysyzbh"));
        }
        return getSuccess(null);
    }

    /*高风险治疗预警接口（CDSS）*/
    @Override
    public String treatHighRiskAlert(Map<String, Object> req) throws Exception {
        isNUll(req, Arrays.asList("PatientId"));
        List<Map<String, Object>> HighRiskAlertList = treatSystemMapper.get_Treat_HighRiskAlert(req);

        return getSuccess(JSONArray.fromObject(HighRiskAlertList));
    }

    /*检验报告获取*/
    @Override
    public String get_Treat_LisReport(Map<String, Object> req) throws Exception {
        isNUll(req, Arrays.asList("PatientId"));
        List<Map<String, Object>> lisReportList = treatSystemMapper.get_Treat_LisReport(req);

        for (Map<String, Object> item : lisReportList) {
            if (ObjectUtils.isEmpty(item.get("ReportNo"))) {
                continue;
            }
            List<Map<String, Object>> lisReportListDetailList = treatSystemMapper.get_Treat_LisReportDetails(item);
            item.put("ReportDetails", lisReportListDetailList);
        }

        return getSuccess(JSONArray.fromObject(lisReportList));
    }

    /*检查报告获取*/
    @Override
    public String get_Treat_PacsReport(Map<String, Object> req) throws Exception {
        isNUll(req, Arrays.asList("PatientId"));
        List<Map<String, Object>> pacsReportList = treatSystemMapper.get_Treat_PacsReport(req);

        return getSuccess(JSONArray.fromObject(pacsReportList));
    }

    /**=========================================================金堂人民医院=============================================================*/
}
